package top.hundreds.oasys.service;

import org.springframework.stereotype.Service;
import top.hundreds.common.crud.service.BaseService;
import top.hundreds.oasys.bean.converter.Converter;
import top.hundreds.oasys.bean.entity.Menu;
import top.hundreds.oasys.bean.enums.MenuStatus;
import top.hundreds.oasys.bean.vo.MenuTreeVo;
import top.hundreds.oasys.bean.vo.MenuVo;
import top.hundreds.oasys.mapper.MenuMapper;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;

/**
 * (Menu)表服务实现类
 *
 * @author lcf
 * @since 2021-01-27 14:59:55
 */
@Service("menuService")
public class MenuService extends BaseService<Menu, MenuMapper> {

    @Resource
    private Converter<Menu, MenuTreeVo> menuTreeVoBuilder;

    @Resource
    private Converter<Menu, MenuVo> menuVoBuilder;

    public List<MenuTreeVo> getTree() {
        return getTreeItem((long) -1);
    }

    private List<MenuTreeVo> getTreeItem(Long id) {
        ArrayList<MenuTreeVo> treeVoList = new ArrayList<>();
        List<Menu> menuList = this.get(Menu.builder().parentId(id).build());
        for (Menu menu : menuList) {
            MenuTreeVo menuTreeVo = new MenuTreeVo();
            menuTreeVoBuilder.buildVo(menu,menuTreeVo);
            menuTreeVo.setStatusName(MenuStatus.formValue(menuTreeVo.getStatus()).getLabel());
            List<MenuTreeVo> treeItem = getTreeItem(menu.getId());
            if(treeItem.size() != 0) {
                menuTreeVo.setChildren(treeItem);
            }
            treeVoList.add(menuTreeVo);
        }
        return treeVoList;
    }

    public List<MenuVo> list() {
        return getChildren((long) -1);
    }

    public List<MenuVo> getChildren(Long parentId) {
        List<MenuVo> menuVoList = new ArrayList<>();
        List<Menu> menuList = get(Menu.builder().parentId(parentId).build());
        for (Menu menu : menuList) {
            MenuVo menuVo = new MenuVo();
            menuVoBuilder.buildVo(menu,menuVo);
            menuVoList.add(menuVo);
            List<MenuVo> children = getChildren(menuVo.getId());
            if(children.size() > 0) {
                menuVoList.addAll(children);
            }
        }
        return menuVoList;
    }


}
